package com.aaa.sso.controller;

import com.aaa.common.entity.User;
import com.aaa.common.util.WebUtil;
import com.aaa.sso.vo.LoginVo;
import com.aaa.common.vo.Result;
import com.alibaba.fastjson.JSON;
import net.bytebuddy.asm.Advice;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @program: aaa-hospital-parent
 * @description:
 * @author: 闫克起
 * @create: 2024-05-20 16:45
 **/
@RestController
@RequestMapping("/sso")
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping("/logout")
    public Result<User> logout(){
        //获取token
        String token = WebUtil.getRequest().getHeader("token");
        redisTemplate.delete("user:login:"+token);
        return  new Result<User>(2000,"退出成功",null);

    }

    @GetMapping("/info")
    public Result<User> info(){
        //获取token
        String token = WebUtil.getRequest().getHeader("token");
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        return new Result<User>(2000,"获取用户信息成功",user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword());
        try {
            subject.login(usernamePasswordToken);
            //1.生成一个令牌---保证唯一标识---根据这个令牌拿到用户信息
            String token = UUID.randomUUID().toString().replace("-", "");
            //2.把用户信息存在redis.  token作为key  用户信息作为value
            User user = (User) subject.getPrincipal();
            //3.存放再redis
            ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
            //存入一个json字符串
            valueOperations.set("user:login:"+token, JSON.toJSONString(user),30, TimeUnit.MINUTES);
            return new Result<String>(2000,"登录成功",token);
        }catch (Exception e){
            return new Result(5000,"账号密码错误",null);
        }

    }

}
